package com.kaiwukj.android.ufamily.mvp.ui.page.mine.face;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.LogUtils;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseActivity;
import com.kaiwukj.android.ufamily.mvp.http.utils.RxUtils;
import com.kaiwukj.android.ufamily.utils.FileUtil;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.vise.face.CameraPreview;
import com.vise.face.DetectorData;
import com.vise.face.DetectorProxy;
import com.vise.face.FaceRectView;
import com.vise.face.ICameraCheckListener;
import com.vise.face.IDataListener;
import com.vise.face.IFaceDetector;
import com.vise.face.SystemFaceDetector;
import com.vise.log.ViseLog;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.UUID;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;

//@Route(path = ARouterUrlKt.ViseFaceActivityUrl)
public class ViseFaceBakActivity extends BaseActivity {

    @BindView(R.id.face_detector_preview)
    CameraPreview mFacePreview;
    @BindView(R.id.face_detector_face)
    FaceRectView mFaceView;
    @BindView(R.id.qtb_vise_face)
    QMUITopBar mTopBar;
    @BindView(R.id.face_detector_distance)
    TextView mFace_detector_distance;
    @BindView(R.id.btn_face_detector_take_photo)
    QMUIRoundButton mUploadBtn;
    private DetectorData mDetectorData;
    private DetectorProxy mDetectorProxy;
    public static String VISE_FACE_IMAGE_DATA = "VISE_FACE_IMAGE_DATA";

    private IDataListener mDataListener = detectorData -> {
        //回调识别到的数据
        mDetectorData = detectorData;
        // mHandler.sendEmptyMessage(0);
        runOnUiThread(() -> {
            if (!isFinishing() && mDetectorData != null) {
                if (mDetectorData.getLightIntensity() == 0) {
                    mUploadBtn.setEnabled(false);
                    mFace_detector_distance.setText("请保证人脸清晰，光线充足情况下拍摄");
                } else {
                    mUploadBtn.setEnabled(true);
                    mFace_detector_distance.setText("已检测到人脸");
                }

            }
        });
    };


    @Override
    protected int getLayoutId() {
        return R.layout.activity_vise_face_bak;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {

    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mTopBar.addLeftBackImageButton().setOnClickListener(view -> onBackPressedSupport());
        mTopBar.setTitle("人脸照片");
        mFaceView.setZOrderOnTop(true);
        mFaceView.getHolder().setFormat(PixelFormat.TRANSLUCENT);
        IFaceDetector mFaceDetector = new SystemFaceDetector();
        ICameraCheckListener mCameraCheckListener = new ICameraCheckListener() {
            @Override
            public void checkPermission(boolean isAllow) {
                //权限是否允许
            }

            @Override
            public void checkPixels(long pixels, boolean isSupport) {
                //手机像素是否满足要求
            }
        };

        //创建代理类，必须传入相机预览界面
        mDetectorProxy = new DetectorProxy.Builder(mFacePreview)
                .setCheckListener(mCameraCheckListener)
                //设置人脸检测实现
                .setFaceDetector(mFaceDetector)
                //设置检测数据回调监听
                .setDataListener(mDataListener)
                //设置绘制人脸识别框界面
                .setFaceRectView(mFaceView)
                //设置是否绘制人脸检测框
                .setDrawFaceRect(true)
                //设置预览相机的相机ID
                .setCameraId(Camera.CameraInfo.CAMERA_FACING_FRONT)
                //设置可检测的最大人脸数
                .setMaxFacesCount(1)
                //设置人脸识别框是否为完整矩形
                .setFaceIsRect(false)
                //设置人脸识别框的RGB颜色
                .setFaceRectColor(Color.rgb(255, 203, 15))
                //创建代理类
                .build();
        // 点击SurfaceView，切换摄相头
        mFacePreview.setOnClickListener(v -> {
            // 只有一个摄相头，不支持切换
            if (Camera.getNumberOfCameras() == 1) {
                return;
            }
            if (mDetectorProxy == null) {
                return;
            }
            mDetectorProxy.closeCamera();
            if (Camera.CameraInfo.CAMERA_FACING_FRONT == mDetectorProxy.getCameraId()) {
                mDetectorProxy.setCameraId(Camera.CameraInfo.CAMERA_FACING_BACK);
            } else {
                mDetectorProxy.setCameraId(Camera.CameraInfo.CAMERA_FACING_FRONT);
            }
            mDetectorProxy.openCamera();
        });


        //拍照上传
        mUploadBtn.setOnClickListener(view -> {
            //   showLoading("正在采集...");
            mUploadBtn.setEnabled(false);
            try {
                mFacePreview.getCamera().takePicture(() -> {

                }, null, (bytes, camera) -> {
                    mFacePreview.getCamera().stopPreview();
                    //saveImage(bytes);
                    dealImage(bytes);
                });
            } catch (Exception e) {
                showMessage("获取照片失败!");
            }

            // mFacePreview.getCamera().take
        });
    }

    private void dealImage(byte[] bytes) {

        subscribe(Observable.create((ObservableOnSubscribe<File>) emitter -> {
            Bitmap bitmap = ImageUtils.bytes2Bitmap(bytes);
            //int quality;
            if (mFacePreview.getCameraId() == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                bitmap = rotaingImageView(360 - mFacePreview.getDisplayOrientation(), bitmap);
                //  quality = 45;
            } else {
                bitmap = rotaingImageView(mFacePreview.getDisplayOrientation(), bitmap);
                //  quality = 10;
            }
            byte[] bytes1 = ImageUtils.compressByQuality(bitmap, 100 * 1024L);
            //byte[] bytes1 = ImageUtils.bitmap2Bytes(result, Bitmap.CompressFormat.JPEG);

            File file = getOutputFile(mContext, "face", UUID.randomUUID() + ".jpg");
            if (FileUtils.createOrExistsFile(file)) {
                boolean isOk = FileIOUtils.writeFileFromBytesByStream(file, bytes1);
                if (isOk) {
                    emitter.onNext(file);
                } else {
                    emitter.onError(new Exception("file compress failed"));
                }
            } else {
                emitter.onError(new FileNotFoundException("face file not found"));
            }

        })
                .doOnSubscribe(act -> showLoading("正在处理..."))
                .doFinally(this::hideLoading)
                .compose(RxUtils.schedulerHelper())
                .subscribe(file -> {
                    // LogUtils.d("path--------------->" + file.getAbsolutePath());
                    LogUtils.d("size--------------->" + FileUtil.getFileSize(file));
                    File tempFile = getOutputFile(null, "face", "a.jpg");
                    FileUtils.copy(file, tempFile);
                    //LogUtils.d("temp--------------------->" + tempFile.getAbsolutePath());
                    //LogUtils.d("path--------------->" + file.getAbsolutePath());
                    //  mPresenter.requestFaceZGToken(file.getName(), file.getAbsolutePath());
                    // faceRegister(file.getPath());
                    showFace(file.getPath());
                    /*ZghlFaceDetection.getInstance().checkFaceNumber(ImageUtils.getBitmap(file), faceNum -> {
                        LogUtils.d("faceNum----------------->" + faceNum);
                        runOnUiThread(() -> {
                            if (faceNum == -404) {
                                LogUtil.e("UpdateFaceCameraActivity", "sdk不支持该机型，无法检测人脸数量，请自行判断该图是否通过");
                                faceRegister(file.getPath());
                                return;
                            }
                            if (faceNum > 1) {
                                showMessage("检测到多张人脸");
                            } else if (faceNum < 1) {
                                showMessage("未检测到人脸");
                            } else {
                                faceRegister(file.getPath());
                            }
                        });
                    });*/


                }, err -> {
                    showMessage("图片处理异常");
                    finish();
                }));


    }

    private void showFace(String facePath) {
        Intent data = new Intent();
        data.putExtra("face", facePath);
        setResult(RESULT_OK, data);
        finish();
    }


    private File getOutputFile(Context context, String dirName, String fileName) {
        File dirFile = new File(getDiskCacheDir(context, dirName));
        if (!dirFile.exists()) {
            if (!dirFile.mkdirs()) {
                ViseLog.d("failed to create directory");
                return null;
            }
        }
        File file = new File(dirFile.getPath() + File.separator + fileName);
        return file;
    }

    private String getDiskCacheDir(Context context, String dirName) {
        //  String cachePath = "";
      /*  if ((Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable())
                && context != null && context.getExternalCacheDir() != null) {
            cachePath = context.getExternalCacheDir().getPath();
        } else {
            if (context != null && context.getCacheDir() != null) {
                cachePath = context.getCacheDir().getPath();
            }
        }*/
        return getCacheDir().getPath() + File.separator + dirName;
    }

    private Bitmap rotaingImageView(int angle, Bitmap bitmap) {
        Matrix matrix = new Matrix();
        matrix.postRotate((float) angle);
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        if (resizedBitmap != bitmap && bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
        }

        return resizedBitmap;
    }

    @Override
    protected void onStop() {
        super.onStop();
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    @Override
    protected void onStart() {
        super.onStart();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mDetectorProxy != null) {
            mDetectorProxy.release();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mDetectorProxy != null) {
            mDetectorProxy.detector();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        System.gc();
    }

}
